<?php

namespace app\common\entity;

use think\Db;
use think\Model;

class GoodsCategory extends Model
{
    /**
     * @var string 对应的数据表名
     */
    protected $table = 'goods_category';

    public static function getAllCate($where = [])
    {
        $entity = new self();
        return $entity->where(array("level" => 0))->where($where)->order('sort asc')->select();
//        return [
//            '1' => '公告',
//            '2' => '新手解答',
////            '3' => '便民'
//        ];
    }

    /*
     * 分页商品列表
     * */
    public function getGoodsCategoryPages($category_id)
    {
        if ($category_id) {
            $pageParam['query']['type'] = $category_id;         //type 分类参数
            $data = $this->where('parent_id', $category_id)->order('sort asc')->paginate(20, false, $pageParam);
        } else {
            $data1 = $this->select();
            $count = count($data1);
            $data = $this->order('sort asc')->paginate(20, $count);
        }

        return $data;
    }

    /*
     * 添加商品分类
     * */
    public function addGoodsCategoryParent($data)
    {
        $entity = new self();
        $entity->category_title = $data['category_title'];
        $entity->parent_id = 0;
        $entity->level = 0;
        $entity->img = $data['photo'];
        $entity->sort = $data['sort'];
        $entity->shoptype = $data['shoptype'];
        return $entity->save();
    }

    /*
     * 添加商品分类
     * */
    public function addGoodsCategorySon($data)
    {
        $entity = new self();
        $entity->category_title = $data['category_title'];
        $entity->parent_id = $data['category_id'];
        $entity->img = $data['photo'];
        $entity->level = 1;
        return $entity->save();
    }

    /*
     * @parem  category_id
     *  根据商品分类ID 获取父类名
     * */
    public function getParentByCategoryId($category_id)
    {
        if ($category_id == 0) {
            return "一级分类";
        }
        $category_title = $this->where(array("category_id" => $category_id))->value('category_title');
        return $category_title;
    }

    public function updateGoodsCategory(GoodsCategory $goodsCategory, $data)
    {
        $goodsCategory->category_title = $data['category_title'];
        $goodsCategory->img = $data['photo'];
        $goodsCategory->sort = $data['sort'];
        $goodsCategory->shoptype = $data['shoptype'];
        return $goodsCategory->save();
    }
}